package com.fablesoft.projectdatacollect.ui;

import android.app.FragmentManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.authentication.utils.ToastUtil;
import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseInfoBean;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.EducationListResponse;
import com.fablesoft.projectdatacollect.bean.IdCardResultResponse;
import com.fablesoft.projectdatacollect.bean.PersonTypeListResponse;
import com.fablesoft.projectdatacollect.bean.TeamResponse;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.interfaces.SwitchListener;
import com.fablesoft.projectdatacollect.ui.fragment.BaseFragment;
import com.fablesoft.projectdatacollect.ui.fragment.FragmentBaseinfo;
import com.fablesoft.projectdatacollect.ui.fragment.FragmentFingerprint;
import com.fablesoft.projectdatacollect.ui.fragment.FragmentIdCard;
import com.fablesoft.projectdatacollect.ui.fragment.FragmentMaterial;
import com.fablesoft.projectdatacollect.ui.fragment.FragmentSmartcard;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.FileUtils;
import com.fablesoft.projectdatacollect.util.Log4jUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import android_serialport_api.SerialPortManager;

public class PersonnelRegisterNewActivity extends BaseRequestActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener, SwitchListener {

    private View back;
    private RadioGroup rgRegister;
    private RadioButton rbStep1;
    private RadioButton rbStep2;
    private RadioButton rbStep3;
    private RadioButton rbStep4;
    private RadioButton rbStep5;
    private FragmentIdCard fragmentIdCard;
    private FragmentFingerprint fragmentFingerprint;
    private FragmentBaseinfo fragmentBaseinfo;
    private FragmentSmartcard fragmentSmartcard;
    private FragmentMaterial fragmentMaterial;
    private BaseFragment currentFragment;
    private FragmentManager fragmentManager;

    public String idNo;
    public IdCardResultResponse result;
    public BaseInfoBean baseInfo;

    private boolean isSuccessFinger;
    private boolean isSuccessMaterial;
    private boolean isSuccessSmartcard;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personnel_register_new);
        openSerialPort();
        initView();
        initFragment();
        initEducationData();
        initPeopleData();
        initTeamData();
    }

    private void initView() {
        /*********************************** view init start **************************************/
        back = findViewById(R.id.back);
        back.setOnClickListener(this);
        rgRegister = (RadioGroup) findViewById(R.id.rg_register);
        rbStep1 = (RadioButton) findViewById(R.id.step1);
        rbStep2 = (RadioButton) findViewById(R.id.step2);
        rbStep3 = (RadioButton) findViewById(R.id.step3);
        rbStep4 = (RadioButton) findViewById(R.id.step4);
        rbStep5 = (RadioButton) findViewById(R.id.step5);
        rgRegister.setOnCheckedChangeListener(this);
        CommonUtils.disableRadioGroup(rgRegister);
    }

    private void initFragment() {
        fragmentManager = getFragmentManager();
        fragmentIdCard = new FragmentIdCard();
        fragmentFingerprint = new FragmentFingerprint();
        fragmentBaseinfo = new FragmentBaseinfo();
        fragmentSmartcard = new FragmentSmartcard();
        fragmentMaterial = new FragmentMaterial();
        fragmentIdCard.setSwitchListener(this);
        fragmentSmartcard.setSwitchListener(this);
        fragmentFingerprint.setSwitchListener(this);
        fragmentBaseinfo.setSwitchListener(this);
        fragmentMaterial.setSwitchListener(this);
        fragmentManager.beginTransaction().add(R.id.content, fragmentIdCard).commit();
        currentFragment = fragmentIdCard;
    }

    @Override
    public void onClick(View v) {
        if (isRepeatClick(v)) {
            return;
        }
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

    }

    @Override
    public void onNext(int position) {
        switch (position) {
            case 1:
                switchFragment(fragmentFingerprint);
                rbStep2.setChecked(true);
                fragmentIdCard.setSerialPort(false);
                break;
            case 2:
                switchFragment(fragmentBaseinfo);
                rbStep3.setChecked(true);
                fragmentFingerprint.setSerialPort(false);
                break;
            case 3:
                switchFragment(fragmentMaterial);
                rbStep4.setChecked(true);
                break;
            case 4:
                switchFragment(fragmentSmartcard);
                rbStep5.setChecked(true);
                fragmentSmartcard.setSerialPort(true);
                break;
        }
    }

    @Override
    public void onLast(int position) {
        switch (position) {
            case 2:
                switchFragment(fragmentIdCard);
                rbStep1.setChecked(true);
                fragmentIdCard.setSerialPort(true);
                break;
            case 3:
                switchFragment(fragmentFingerprint);
                rbStep2.setChecked(true);
                fragmentFingerprint.setSerialPort(true);
                break;
            case 4:
                switchFragment(fragmentBaseinfo);
                rbStep3.setChecked(true);
                break;
            case 5:
                switchFragment(fragmentMaterial);
                rbStep4.setChecked(true);
                fragmentSmartcard.setSerialPort(false);
                break;
        }
    }

    @Override
    public void onSubmitBaseInfo() {
        fragmentBaseinfo.submitBaseInfo();
    }

    @Override
    public void onSubmitOthers() {
        showDialog();
        fragmentFingerprint.submitFingerprintInfo();
        fragmentMaterial.submitMaterials();
        fragmentSmartcard.submitSmartCard();
    }

    @Override
    public void onSubmitStatus(int flag, boolean isSuccess, boolean isCancel) {
        if (isCancel) {
            ToastUtil.showToast(this, "人员信息采集失败!");
            dismissDialog();
            fragmentSmartcard.getBtSubmit().setClickable(true);
            return;
        }
        switch (flag) {
            case CommonUtils.UPLOAD_FINGERPRINT_IMAGE:
                isSuccessFinger = true;
                break;
            case CommonUtils.UPLOAD_CERTIFICATER_IMAGE:
                isSuccessMaterial = true;
                break;
            case CommonUtils.UPLOAD_SMART_CARD:
                isSuccessSmartcard = true;
                break;
        }
        if (isSuccessFinger && isSuccessMaterial && isSuccessSmartcard) {
            ToastUtil.showToast(this, "人员信息采集成功！");
            dismissDialog();
            finish();
        }
    }

    private void switchFragment(BaseFragment fragment) {
        if (currentFragment != fragment) {
            if (!fragment.isAdded()) {
                fragmentManager.beginTransaction().hide(currentFragment)
                        .add(R.id.content, fragment).commit();
            } else {
                fragmentManager.beginTransaction().hide(currentFragment).show(fragment).commit();
            }
            currentFragment = fragment;
        }
    }

    public void showDialog() {
        createLoadingDialog(PersonnelRegisterNewActivity.this);
        showDialog("提交中");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        fragmentIdCard.setSerialPort(false);
        fragmentFingerprint.setSerialPort(false);
        fragmentSmartcard.setSerialPort(false);
        if (SerialPortManager.getInstance().isOpen()) {
            SerialPortManager.getInstance().closeSerialPort();
        }
        FileUtils.deleteFiles(Environment.getExternalStorageDirectory() + CommonUtils.TAKE_PHOTO_PATH);
    }

    // 初始化人员种类
    private void initPeopleData() {
        HttpThread httpThread = null;
        try {
            httpThread = new HttpThread(Config.GET_BASEINFO_URL + URLEncoder.encode("人员种类", "UTF-8"),
                    new HttpListener() {
                        @Override
                        public void onRequestFinish(BaseResponse response) {
                            Message msg = mHandler.obtainMessage();
                            msg.obj = response;
                            msg.what = CommonUtils.GET_PERSONTYPE_CODE;
                            mHandler.sendMessage(msg);
                        }

                        @Override
                        public void onNotLogin(BaseResponse response) {
                        }
                    }, PersonTypeListResponse.class, true);
        } catch (UnsupportedEncodingException e) {
            Log4jUtil.e(e.toString());
            e.printStackTrace();
        }
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    // 初始化学历
    private void initEducationData() {
        HttpThread httpThread = null;
        try {
            httpThread = new HttpThread(Config.GET_BASEINFO_URL + URLEncoder.encode("学历", "UTF-8"),
                    new HttpListener() {
                        @Override
                        public void onRequestFinish(BaseResponse response) {
                            Message msg = mHandler.obtainMessage();
                            msg.obj = response;
                            msg.what = CommonUtils.GET_EDUCATION_CODE;
                            mHandler.sendMessage(msg);
                        }

                        @Override
                        public void onNotLogin(BaseResponse response) {
                        }
                    }, EducationListResponse.class, true);
        } catch (UnsupportedEncodingException e) {
            Log4jUtil.e(e.toString());
            e.printStackTrace();
        }
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    // 初始化班组
    private void initTeamData() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapParams = new HashMap<>();
        mapParams.put("orgId", MyApplication.getInstance().getOrgId());
        map.put("page", 0);
        map.put("size", 0);
        map.put("mapParams", mapParams);
        HttpThread httpThread = new HttpThread(Config.GET_TEAM_URL, new HttpListener() {
            @Override
            public void onRequestFinish(BaseResponse response) {
                Message msg = mHandler.obtainMessage();
                msg.obj = response;
                msg.what = CommonUtils.GET_TEAM_CODE;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onNotLogin(BaseResponse response) {
            }
        }, map, TeamResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CommonUtils.GET_PERSONTYPE_CODE:
                    if (msg.obj == null) {
                        return;
                    }
                    PersonTypeListResponse personTypeListResponse = (PersonTypeListResponse) msg.obj;
                    if (personTypeListResponse.getRows() != null) {
                        fragmentBaseinfo.personTypeList.addAll(personTypeListResponse.getRows());
                    }
                    break;
                case CommonUtils.GET_EDUCATION_CODE:
                    if (msg.obj == null) {
                        return;
                    }
                    EducationListResponse educationListResponse = (EducationListResponse) msg.obj;
                    if (educationListResponse.getRows() != null) {
                        fragmentBaseinfo.educationList.addAll(educationListResponse.getRows());
                    }
                    break;
                case CommonUtils.GET_TEAM_CODE:
                    if (msg.obj == null) {
                        return;
                    }
                    TeamResponse teamResponse = (TeamResponse) msg.obj;
                    if (teamResponse.getRows() != null) {
                        fragmentBaseinfo.teamList.addAll(teamResponse.getRows());
                    }
                    break;
            }
        }
    };

}
